//
//  ByLogTestVC.m
//  laserdevice_ios
//
//  Created by pro on 17/1/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByLogTestVC.h"

#import "ByBlueToothHandleModel.h"

@interface ByLogTestVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIButton *cleanButton;
@property (nonatomic, strong) UIButton *beginButton;
@property (nonatomic, strong) UIButton *importButton;
@property (nonatomic, strong) UITextView *logView;

@property (nonatomic, copy) NSString *keyTitle;

@property (nonatomic, strong) NSMutableString *dataStr;

@end

@implementation ByLogTestVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"蓝牙日志";
    
    [self addLeftBackBarButtonItem];
    
    self.dataStr = [NSMutableString string];
    
    self.keyTitle = @"当前日志打印：单次测量";
    [self createTableView];
    [self createViews];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [ByCoreToolAlert hideHud];
}
// 创建表视图
- (void)createTableView {
    
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 160) style:UITableViewStylePlain];
    self.table.backgroundColor = [UIColor colorWithWhite:0.96 alpha:1];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    
    self.table.scrollEnabled = NO;
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = FONT(14);
    }
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"单次测量";
    }
    if (indexPath.row == 1) {
        cell.textLabel.text = @"实时测量";
    }
    if (indexPath.row == 2) {
        cell.textLabel.text = @"数据导入";
    }
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    label.backgroundColor = [UIColor lightGrayColor];
    label.font = B_FONT(18);
    label.text = @"";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    
    label.text = self.keyTitle;
    
    return label;
}



// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _beginButton.hidden = YES;
    
    if (indexPath.row == 0) {
        self.keyTitle = @"当前日志打印：单次测量";
        [self logSingle];
    }
    if (indexPath.row == 1) {
        self.keyTitle = @"当前日志打印：实时测量";
        _beginButton.hidden = NO;
    }
    if (indexPath.row == 2) {
        self.keyTitle = @"当前日志打印：数据导入";
        [self logHistory];
    }
    
    [self.table reloadData];
}


- (void)createViews {
    
    _cleanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cleanButton.frame = CGRectMake(0, self.table.bottom + 10, 60, 30);
    _cleanButton.right = self.view.width - 10;
    _cleanButton.backgroundColor = [UIColor lightGrayColor];
    [_cleanButton setTitle:@"清空" forState:UIControlStateNormal];
    [_cleanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_cleanButton addTarget:self action:@selector(clean) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cleanButton];
    
    _beginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _beginButton.frame = CGRectMake(0, self.table.bottom + 10, 60, 30);
    _beginButton.left = 10;
    _beginButton.backgroundColor = [UIColor lightGrayColor];
    [_beginButton setTitle:@"开始" forState:UIControlStateNormal];
    [_beginButton setTitle:@"结束" forState:UIControlStateSelected];
    [_beginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_beginButton addTarget:self action:@selector(begin:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_beginButton];
    _beginButton.hidden = YES;
    
    _logView = [[UITextView alloc] initWithFrame:CGRectMake(5, _cleanButton.bottom + 10, SCREEN_WIDTH - 10, SCREEN_HEIGHT - 64 - (_cleanButton.bottom + 10))];
    [self.view addSubview:_logView];
    _logView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _logView.layer.borderWidth = 1;
    
}


- (void)clean {
    
    self.dataStr = [NSMutableString string];
    self.logView.text = @"";
}
- (void)logHistory {
    
    if (![ByBlueToothHandleModel shareInstance].characteristic) {
        [ByCoreToolAlert showFailureWithText:STRING(@"qinglianjielanya")];
        return;
    }
    
    // 正式版需要，测试的时候不惜要
    [ByCoreToolAlert showLoadind:@"正在导入蓝牙历史数据..."];
    
    [self performSelector:@selector(cancel) withObject:nil afterDelay:10];

    [[ByBlueToothHandleModel shareInstance] getHistoryMeasure:^(NSString *dataHex) {
        
        [ByCoreToolAlert hideHud];

        [self.dataStr appendFormat:@"%@\n", dataHex];
        
        _logView.text = self.dataStr;
        
        // 如果能再次收到数据，则不用绘制图标
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        // 如果3秒内无法再收到数据，则默认数据完毕
        [self performSelector:@selector(operationHistoryData) withObject:nil afterDelay:3];
    }];
}
- (void)operationHistoryData {
    
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cancel) object:nil];
    // 停止接收数据
    [[ByBlueToothHandleModel shareInstance] closeHistoryMeasure];
    
}
- (void)cancel {
    [ByCoreToolAlert showFailureWithText:@"失败"];

    // 停止接收数据
    [[ByBlueToothHandleModel shareInstance] closeHistoryMeasure];

}

- (void)logSingle {
    
    if (![ByBlueToothHandleModel shareInstance].characteristic) {
        [ByCoreToolAlert showFailureWithText:STRING(@"qinglianjielanya")];
        return;
    }
    
//    [[ByBlueToothHandleModel shareInstance] startDistanceMeasure:^(NSString *dataHex) {
//        
//
//        [self.dataStr appendFormat:@"%@\n", dataHex];
//        
//        _logView.text = self.dataStr;
    
//        // 接收到应答信号则不做处理
//        if ([dataHex isEqualToString:@"F0"] || [dataHex isEqualToString:@"f0"]) {
//            return;
//        }
//        // 接收到的传递产品信息的数据，则不做处理
//        if (dataHex.length == 18 * 2 && [[dataHex substringWithRange:NSMakeRange(28, 4)] isEqualToString:@"5648"]) {
//            return;
//        }
//
//        [self.dataString appendString:dataHex];
//        // 接收到以FA为后缀的，说明数据接收完成
//        NSLog(@"%@", self.dataString);
//        if ([self.dataString hasSuffix:@"FA"] || [self.dataString hasSuffix:@"fa"]) {
//            
//            NSString *str = [[self.dataString componentsSeparatedByString:@"fa"] firstObject];
//            self.dataString = [NSMutableString stringWithFormat:@"%@fa", str];
//
//            ByUISceneOperateView *operateView = [self.view viewWithTag:10];
//            
//            // 实用数据
//            NSString *distance = [ByBlueToothDataOperationModel displayDistanceOperation:self.dataString];
//            
//            // 数据可用，则添加到数据字典
//            if (distance) {
//                [operateView setDistance:distance];
//            }
//            
//            // 把可变数据字符串清空
//            self.dataString = [[NSMutableString alloc] init];
//        }
//        
//    }];

}
- (void)begin:(UIButton *)sender {
    
    if (![ByBlueToothHandleModel shareInstance].characteristic) {
        [ByCoreToolAlert showFailureWithText:STRING(@"qinglianjielanya")];
        return;
    }
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [[ByBlueToothHandleModel shareInstance] startRealTimeMeasure:^(NSString *dataHex) {
            
            [self.dataStr appendFormat:@"%@\n", dataHex];
            
            _logView.text = self.dataStr;
            
            // 接收到应答信号则不做处理
            if ([dataHex isEqualToString:@"F0"] || [dataHex isEqualToString:@"f0"]) {
                return;
            }
            
//            [self.dataString appendString:dataHex];
//            // 接收到以FA为后缀的，说明数据接收完成
//            if ([self.dataString hasSuffix:@"FA"] || [self.dataString hasSuffix:@"fa"]) {
//                
//                
//                // 收到数据后，重置时间
//                _noDataTime = 0;
//                
//                
//                // 实用数据
//                NSNumber *dataNumber = [ByBlueToothDataOperationModel real_timeMeasureDataOperation:self.dataString];
//                
//                
//                // 数据可用，则添加到数据字典
//                if (dataNumber) {
//                    [self.dataArray addObject:dataNumber];
//                    
//                    // 提醒
//                    [self isShouldAlert:dataNumber];
//                }
//                
//                // 把可变数据字符串清空
//                self.dataString = [[NSMutableString alloc] init];
//                
//                // 重绘折线图
//                self.chart.totalMeasureValues = [self.dataArray copy];
//            }
            
        }];
    } else {
        [[ByBlueToothHandleModel shareInstance] closeRealTimeMeasure];
        NSLog(@"关闭实时测量");
    }

}

@end
